import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from './router'
import { isObjectArray } from './utils'

function redirectToLogin(next, to) {
  if (process.env.NODE_ENV === 'development') {
    next(`/login?redirect=${to.path}`)
  } else {
    window.location.href = '/'
  }
}

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/test/app-store'] // no redirect whitelist

if (process.env.NODE_ENV === 'development') {
  whiteList.push('/login')
}

router.beforeEach(async (to, from, next) => {
  debugger
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoutes = isObjectArray(store.getters.addRoutes)
      const hasUserInfo = store.getters.userInfo
      if (hasRoutes && hasUserInfo) {
        next()
      } else {
        try {
          store.dispatch('app/setCountries')
          store.dispatch('app/getOrgs')
          await store.dispatch('user/getInfo')
          const routes = await store.dispatch('permission/generateRoutes')
          router.addRoutes([
            ...routes,
            ...asyncRoutes,
            { path: '*', redirect: '/404', hidden: true }
          ])

          next({ ...to, replace: true })
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          redirectToLogin(next, to)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    console.log('==============================================')
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      redirectToLogin(next, to)
      NProgress.done()
    }
  }
  NProgress.done()
})

router.afterEach((to, from) => {
  console.log(to, from)

  // finish progress bar
  NProgress.done()
})
